#include "session.h"
#include "registry.h"

namespace cs
{
	session::session(boost::asio::io_service& io_service)
    : socket_(io_service) {}

	boost::asio::ip::tcp::socket& session::socket()
	{
		return socket_;
	}

	void session::start()
	{

		service_registry::instance().add_session(shared_from_this());
		boost::asio::async_read(socket_,
			boost::asio::buffer(read_msg_.get_header().data(), message::header_length),
			boost::bind(&session::handle_read_header, shared_from_this(),
			boost::asio::placeholders::error));
	}

	void session::deliver(const message& msg)
	{
		/*
		bool write_in_progress = !write_msgs_.empty();
		write_msgs_.push_back(msg);
		if (!write_in_progress) {
			boost::asio::async_write(socket_,
				boost::asio::buffer(write_msgs_.front().get_header().data(),
				message::header_length),
				boost::bind(&session::handle_write, shared_from_this(),
				boost::asio::placeholders::error));
		}
		*/
	}

	void session::handle_read_header(const boost::system::error_code& error)
	{
		if (!error && read_msg_.decode_header()) {
			char* buffer = new char[read_msg_.size()];
			boost::asio::async_read(socket_,
				boost::asio::buffer(buffer, read_msg_.size()),
				boost::bind(&session::handle_read_body, shared_from_this(),
				boost::asio::placeholders::error));
			read_msg_.set(std::string(buffer, read_msg_.size()));
			delete buffer;
		} else {
			//registry_.leave(shared_from_this());
		}
	}
	
	void session::handle_read_body(const boost::system::error_code& error)
	{
		if (!error) {
		//	registry_.deliver(read_msg_);
			boost::asio::async_read(socket_,
				boost::asio::buffer(read_msg_.get_header().data(), message::header_length),
				boost::bind(&session::handle_read_header, shared_from_this(),
				boost::asio::placeholders::error));
		} else {
		//	registry_.leave(shared_from_this());
		}
	}

	void session::handle_write(const boost::system::error_code& error)
	{
		/*
		if (!error) {
			write_msgs_.pop_front();
			if (!write_msgs_.empty()) {
				boost::asio::async_write(socket_,
					boost::asio::buffer(write_msgs_.front().get_header().data(),
					message::header_length),
					boost::bind(&session::handle_write, shared_from_this(),
					boost::asio::placeholders::error));
			}
		} else {
		//	registry_.leave(shared_from_this());
		}
		*/
	}
}